//全局状态获取hook
import {AppDispatch, RootState} from "../store";
import {TypedUseSelectorHook, useDispatch, useSelector} from "react-redux";
import {useEffect, useState} from "react";
import {dictCategory, dictDetail,} from "../api";
import {DictCategoryType} from "../util/publicType";
import {AxiosResponse} from "axios";
import {message} from "antd";

// 动作执行
export const useAppDispatch: () => AppDispatch = useDispatch;
// 状态获取
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;

//分类数据
export const useDictCategory = () => {
    // 原始数据
    const [category, setCategory] = useState<DictCategoryType[]>([]);
    // 下拉更改数据
    const [optionCategory, setOptionCategory] = useState<Array<{ label: string, value: string }>>([]);
    // menu菜单
    const [menu, setMenu] = useState<Array<DictCategoryType>>([]);
    // info,获取权限信息
    const infoData = useAppSelector((state: RootState) => state.info);
    useEffect(() => {
        // 分类请求
        dictCategory().then(async (r: AxiosResponse) => {
            if (infoData.id) {
                let data: DictCategoryType[] = r.data.data.data;
                const menuData: Array<any> = [];
                for (const v of data) {
                    if (infoData.jurisdictions.findIndex(item => item.name === v.name) >= 0) {
                        const childrenData = await dictDetail(v.id);
                        menuData.push({...v, child: childrenData.data.data.data});
                    }
                }
                setMenu(menuData);
                setOptionCategory(data.map(v => {
                    return {
                        label: v.name,
                        value: v.id
                    }
                }))
                setCategory(data);
            }

        })
    }, [infoData])
    return {category, optionCategory, menu};
}